package com.xingdata.jjxc.guide;

import java.util.HashMap;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.activity.LoginActivity;
import com.xingdata.jjxc.activity.MainActivity;
import com.xingdata.jjxc.activity.TokenEntity;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.enty.UpdateInfoEntity;
import com.xingdata.jjxc.enty.UserEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.utils.Code;
import com.xingdata.jjxc.utils.SP;
import com.xingdata.jjxc.utils.StringUtil;
import com.xingdata.jjxc.utils.SystemInfo;
import com.xingdata.jjxc.views.CustomDialog;

/**
 * 
 * @{# SplashActivity.java Create on 2013-5-2 下午9:10:01
 * 
 *     class desc: 启动画面 (1)判断是否是首次加载应用--采取读取SharedPreferences的方法
 *     (2)是，则进入GuideActivity；否，则进入MainActivity (3)3s后执行(2)操作
 * 
 *     <p>
 *     Copyright: Copyright(c) 2013
 *     </p>
 * @Version 1.0
 * @Author <a href="mailto:gaolei_xj@163.com">Leo</a>
 * 
 * 
 */
public class SplashActivity extends Base1Activity {
	
	final static String TAG ="SplashActivity";
	/**
	 * 判断是否是首次加载应用
	 */
	boolean isFirstIn = false;
	private static final int GO_HOME = 1000;
	private static final int GO_GUIDE = 1001;
	// 延迟3秒
	private static final long SPLASH_DELAY_MILLIS = 3000;

	private static final String SHAREDPREFERENCES_NAME = "first_pref";

	/**
	 * Handler:跳转到不同界面
	 */
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GO_HOME:
				// goHome();
				Log.d(TAG, "mHandler"+"GO_HOME");
				do_Post_softupdate();
				break;
			case GO_GUIDE:
				Log.d(TAG, "mHandler"+"GO_GUIDE");
				goGuide();
				break;
			}
			super.handleMessage(msg);
		}
	};

	/** 升级 */
	private UpdateInfoEntity updateInfoEntity = null;

	@Override
	protected int getContentViewId() {
		// TODO Auto-generated method stub
		return R.layout.splash;
	}

	@Override
	protected String getTitleText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		init();
	}

	private void init() {
		// 读取SharedPreferences中需要的数据
		// 使用SharedPreferences来记录程序的使用次数
		SharedPreferences preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_PRIVATE);

		// 取得相应的值，如果没有该值，说明还未写入，用true作为默认值
		isFirstIn = preferences.getBoolean("isFirstIn", true);

		// 判断程序与第几次运行，如果是第一次运行则跳转到引导界面，否则跳转到主界面
		if (!isFirstIn) {
			// 使用Handler的postDelayed方法，3秒后执行跳转到MainActivity
			mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS);
		} else {
			mHandler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS);
		}

	}

	private void goHome() {
		Intent intent = new Intent(SplashActivity.this, MainActivity.class);
		SplashActivity.this.startActivity(intent);
		SplashActivity.this.finish();
	}

	private void goGuide() {
		Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
		SplashActivity.this.startActivity(intent);
		SplashActivity.this.finish();
	}

	private void do_Post_softupdate() {
		Log.d(TAG, "do_Post_softupdate");
		String url = "http://jjxc.hudim.com/index.php/Hud/public/softupdate";
		paramsMap = new HashMap<String, String>();
		paramsMap.put("version", SystemInfo.getAPKVersionName(this));
		// paramsMap.put("version", "0.01");
		paramsMap.put("package_name", "com.xingdata.jjxc");
		paramsMap.put("platform", "Android");
		
		HttpUtil.getInstance(this).Post(url, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				updateInfoEntity = JSON.parseObject(respEntity.getResult(), UpdateInfoEntity.class);
				showUpadateDialog();
			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {
				
				UserEntity user = SP.getUserInfo(SplashActivity.this);
				if (user != null) {
					if (user.getMobile().length() != 0 && user.getPw().length() != 0) {
						showProgressDialog("正在登录...");
						doPost_login(user.getMobile(), user.getPw());
					} else {
						startActivity(new Intent(SplashActivity.this, LoginActivity.class));
						finish();
					}

				}
				
			}
		});
	}

	public void showUpadateDialog() {
		CustomDialog.Builder builder = new CustomDialog.Builder(this, R.layout.dialog_update_info);
		StringBuffer buffer = new StringBuffer();
		buffer.append("发现新版本" + updateInfoEntity.getVersion_no() + "\n\n");
		buffer.append("升级内容 " + "\n");
		buffer.append(updateInfoEntity.getVersion_desc().replaceAll(" ", "\n") + "\n");
		buffer.append("总大小：" + StringUtil.formatSize(updateInfoEntity.getFile_size()));
		builder.setMessage(buffer.toString());
		builder.setTitle("提示");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateInfoEntity.getVersion_path())));
				dialog.dismiss();
			}
		});

		builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		});

		builder.create().show();
	}

	
	/** 1、登陆 2、登陆好了直接进界面 */
	private void doPost_login(final String mobile, final String password) {
		if (isNetworkConnected() == false) {
			showToast("网络连接断开，请检查网络");
			return;
		}
		
		paramsMap = new HashMap<String, String>();
		paramsMap.put("mobile", mobile);
		paramsMap.put("password", password);
		
		mHttpUtil.Post(App.ZZD_REQUEST_LOGIN, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity entity) {
				dismissProgressDialog();
				// SharedPreTools.putString(LoginActivity.this,
				// Common.USERNAME, mobile);
				// SharedPreTools.putString(LoginActivity.this,
				// Common.PASSWORD,Jni.Jni_encryptionStr(password,
				// mobile));
				UserEntity user = JSON.parseObject(entity.getResult(), UserEntity.class);
				// 获取Token
				TokenEntity tokenEntity = new TokenEntity();
				tokenEntity.setToken(Code.accessToken(mobile, password, user.getUserid()));
				SystemInfo.setTokenEntity(tokenEntity);
				user.setMobile(mobile);
				user.setToken(tokenEntity.getToken());
				user.setPw(password);
				SP.saveUserInfo(SplashActivity.this, user);
				// baocuo
				// carHudlist =
				// JUtils.getcarHudList(entity.getHudlist());
				// SP.saveHudInfo(LoginActivity.this,
				// entity.getHudlist());
				nextController();
			}

			@Override
			public void onFailure(String result) {
				showToast(result);
				dismissProgressDialog();
				startActivity(new Intent(SplashActivity.this, LoginActivity.class));
				finish();
			}

			@Override
			public void onLoading(int vurrent) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void nextController() {
		startActivity(new Intent(SplashActivity.this, MainActivity.class));
		finish();
	};

}
